package com.erainm.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * Created by erainm on 2021/9/9 9:27 上午.
 *
 * @Description TODO:
 **/
public class MyConsumer1 {
    public static void main(String[] args) {
        Map<String, Object> configs = new HashMap<>();
        configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"lg04:9092");
        // 使用常量代替手写的字符串，配置key的反序列化器
        configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
        // 配置value的反序列化器
        configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        // 配置消费组ID
        configs.put(ConsumerConfig.GROUP_ID_CONFIG,"consumer_demo1");
        // 如果找不到当前消费者的有效偏移量，则自动重制到最开始
        // latest表示直接重制到消息偏移量的最后一个
        configs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");

        KafkaConsumer<Integer, String> consumer = new KafkaConsumer<>(configs);

        consumer.subscribe(Arrays.asList("topic_1"));

        while (true) {
            // 如果主题中没有可以消费的消息 ，则改方法可以放到while循环中，没过3秒重新拉取一次
            // 如果还没有拉取到，过3秒再次拉取，防止while循环太密集的poll调用。

            // 会批量从主题的分区拉取消息
            ConsumerRecords<Integer, String> consumerRecords = consumer.poll(3_000);

            consumerRecords.forEach(new Consumer<ConsumerRecord<Integer, String>>() {
                @Override
                public void accept(ConsumerRecord<Integer, String> record) {
                    System.out.println(
                            record.topic() + "\t"
                                    + record.partition() + "\t"
                                    + record.offset() + "\t"
                                    + record.key() + "\t"
                                    + record.value());
                }
            });
        }
//        consumer.close();
    }
}
